/*******************************************************************************
 * Copyright (c) 2004, 2007 Mylyn project committers and others.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *******************************************************************************/

package org.eclipse.mylyn.rememberthemilk.ui.wizards;

import java.net.MalformedURLException;
import java.net.URL;

import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.mylyn.commons.net.AuthenticationCredentials;
import org.eclipse.mylyn.commons.net.AuthenticationType;
import org.eclipse.mylyn.rememberthemilk.core.RTMCorePlugin;
import org.eclipse.mylyn.rememberthemilk.core.RTMLog;
import org.eclipse.mylyn.rememberthemilk.core.client.RTMClient;
import org.eclipse.mylyn.rememberthemilk.ui.Logger;
import org.eclipse.mylyn.tasks.core.TaskRepository;
import org.eclipse.mylyn.tasks.ui.wizards.AbstractRepositorySettingsPage;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Label;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.browser.IWorkbenchBrowserSupport;

/**
 * @author Steffen Pingel
 */
public class RTMRepositorySettingsPage extends AbstractRepositorySettingsPage {
	private static final String TITLE = "Remember The Milk";

	private static final String DESCRIPTION_LABEL = "The Mylyn Remember The Milk repository connector does not use your RTM user name\n" +
													"and password to validate. Instead it gives you a link to an RTM page which you will be\n" +
													"asked to log in to. It will then ask you if you want to authorize API Application.\n";

	private static final String DESCRIPTION = "Authorize the Mylyn Remember The Milk repository";

	private String authToken;

	private boolean valid = false;

	public RTMRepositorySettingsPage(TaskRepository taskRepository) {
		super(TITLE, DESCRIPTION, taskRepository);
	}

	@Override
	protected void createSettingControls(Composite parent) {
		GridLayout layout = new GridLayout(1, false);
		parent.setLayout(layout);

		Label label = new Label(parent, SWT.FILL);
		final RTMClient client = RTMCorePlugin.getDefault().getConnector().getClientManager().getRepository(getRepository());
		if (isValid(client)) {
			label.setText("MylynRememberTheMilk is authorized");
			TaskRepository repo = getRepository();
			// There are times when no repository has been created yet,
			// Usually when this is the first time creating one.
			if (repo != null) {
				AuthenticationCredentials cred = getRepository().getCredentials(AuthenticationType.REPOSITORY);
				if (cred != null) {
					setAuthToken(cred.getUserName());
				} else {
					setAuthToken(getRepository().getUserName());
				}
			} else {
				// since we do not use user names the user supplies, make up one
				setAuthToken("dummy user");
			}
		} else {
			label.setText(DESCRIPTION_LABEL);

			Button openAuthUrlButton = new Button(parent, SWT.PUSH);
			openAuthUrlButton.setText("Click here to begin autorization");
			openAuthUrlButton.addSelectionListener(new SelectionAdapter() {
				@Override
				public void widgetSelected(SelectionEvent e) {
					String authUrl = client.beginAuthorization();

					IWorkbenchBrowserSupport support = PlatformUI.getWorkbench().getBrowserSupport();
					try {
						support.getExternalBrowser().openURL(new URL(authUrl));
					} catch (PartInitException e1) {
						Logger.logError(e1);
					} catch (MalformedURLException e1) {
						Logger.logError(e1);
					}
				}
			});
			Label finishLabel = new Label(parent, SWT.FILL);
			finishLabel.setText("When you have authorized the application click the complete authorization button to finish.");

			Button completeAuthButton = new Button(parent, SWT.PUSH);
			completeAuthButton.setText("Complete Authorization");
			completeAuthButton.addSelectionListener(new SelectionAdapter() {
				@Override
				public void widgetSelected(SelectionEvent e) {
					try {
						String authToken = client.completeAuthorization();
						setAuthToken(authToken);
						valid = true;
						setMessage("Mylyn Remember The Milk has been authorized");
						if (getWizard() != null) {
							getWizard().getContainer().updateButtons();
						}
					} catch (CoreException ex) {
						RTMLog.log(ex.getStatus());
						setErrorMessage("Authorization was not completed. Check the Error Log.");
					}
				}
			});

			Button validateAuthorization = new Button(parent, SWT.PUSH);
			validateAuthorization.setText("Click here to check the validation status");
			validateAuthorization.addSelectionListener(new SelectionAdapter() {
				@Override
				public void widgetSelected(SelectionEvent e) {
					if (isValid(client)) {
						setMessage("Mylyn Remember The Milk has been authorized");
					} else {
						setErrorMessage("Mylyn Remember The Milk is not authorized");
					}
				}
			});
		}
		addProxy(parent);
	}

	/**
	 * We have overloaded the default routine to create the settings
	 * composite, but we need the proxy information, so use the default
	 * routine and only show the proxy controls.
	 *
	 * @param parent Parent composite which we will add the default panel
	 */
	private void addProxy(Composite parent) {
		Composite childComposite = new Composite(parent, SWT.NONE);
		super.createSettingControls(childComposite);
		Control[] oldControls = childComposite.getChildren();
		for (int i = 0; i <= 11; i++) {
			oldControls[i].setVisible(false);
		}
		oldControls[13].setVisible(false);
	}

	protected void setAuthToken(String authToken) {
		this.authToken = authToken;
	}

	private boolean isValid(RTMClient client) {
		valid = client.isAuthorized();
		return valid;
	}

	@Override
	public String getConnectorKind() {
		return RTMCorePlugin.REPOSITORY_KIND;
	}

	@Override
	protected IStatus validate() {
		System.out.println("validating");
		return null;
	}

	@Override
	public String getRepositoryUrl() {
		// TODO Auto-generated method stub
		return "http://www.rememberthemilk.com";
	}

	@Override
	public String getUserName() {
		return authToken;
	}

	@Override
	public String getPassword() {
		return authToken;
	}
//
//	private static final String TITLE = "Remember The Milk Repository Settings";
//
//	private static final String DESCRIPTION = "Example: http://trac.edgewall.org";
//
//	public RTMRepositorySettingsPage(TaskRepository repositoryUi) {
//		super(TITLE, DESCRIPTION, repositoryUi);
//
//		setNeedsAnonymousLogin(false);
//		setNeedsEncoding(false);
//		setNeedsTimeZone(false);
//	}
//
//	@Override
//	protected void createAdditionalControls(final Composite parent) {
//		Button createAuthUrlButton = new Button(parent, SWT.PUSH);
//		createAuthUrlButton.setText("Open Remember The Milk Authorization Page");
//	}
//
//	@Override
//	protected void createSettingControls(Composite parent) {
//		// TODO Auto-generated method stub
////		super.createSettingControls(parent);
//	}
//
//	@Override
//	public boolean isPageComplete() {
//		// make sure "Automatic" is not selected as a version
//		return super.isPageComplete();
//	}
//
//	@Override
//	protected boolean isValidUrl(String name) {
//		if ((name.startsWith(URL_PREFIX_HTTPS) || name.startsWith(URL_PREFIX_HTTP)) && !name.endsWith("/")) {
//			try {
//				new URL(name);
//				return true;
//			} catch (MalformedURLException e) {
//			}
//		}
//		return false;
//	}
//
//	// public for testing
//	public class RTMValidator extends Validator {
//
//		private final String repositoryUrl;
//
//		private final TaskRepository taskRepository;
//
//		final String username;
//
//		final String password;
//
//		final Proxy proxy;
//
//		public RTMValidator(TaskRepository taskRepository) {
//			this.repositoryUrl = taskRepository.getUrl();
//			this.taskRepository = taskRepository;
//
//			this.username = this.taskRepository.getUserName();
//			this.password = this.taskRepository.getPassword();
//			this.proxy = null;//this.taskRepository.getProxy();
//		}
//
//		@Override
//		public void run(IProgressMonitor monitor) throws CoreException {
//			try {
//				//validate(Provider.of(monitor));
//				validate(monitor);
//			} catch (MalformedURLException e) {
//				throw new CoreException(RepositoryStatus.createStatus(repositoryUrl, IStatus.ERROR,
//						RTMUIPlugin.PLUGIN_ID, INVALID_REPOSITORY_URL));
//			} catch (RTMLoginException e) {
//				Logger.logError("exceptino in login", e);
//				throw new CoreException(RepositoryStatus.createStatus(repositoryUrl, IStatus.ERROR,
//						RTMUIPlugin.PLUGIN_ID, INVALID_LOGIN));
//			} catch (RTMPermissionDeniedException e) {
//				throw new CoreException(RepositoryStatus.createStatus(repositoryUrl, IStatus.ERROR,
//						RTMUIPlugin.PLUGIN_ID, "Insufficient permissions for selected access type."));
//			} catch (RTMException e) {
//				String message = "No RTM repository found at url";
//				if (e.getMessage() != null) {
//					message += ": " + e.getMessage();
//				}
//				throw new CoreException(RepositoryStatus.createStatus(repositoryUrl, IStatus.ERROR,
//						RTMUIPlugin.PLUGIN_ID, message));
//			}
//
//		}
//
//		public void validate(IProgressMonitor monitor) throws MalformedURLException, RTMException {
//			URL url = new URL(repositoryUrl);
//			RTMClient client = new RTMClient(url, username, password, proxy);
//
//			client.validate();
//		}
//	}
//
//	@Override
//	protected Validator getValidator(TaskRepository repository) {
//		return new RTMValidator(repository);
//	}
//
//	@Override
//	public String getConnectorKind() {
//		// TODO Auto-generated method stub
//		return RTMCorePlugin.REPOSITORY_KIND;
//	}

	@Override
	protected void createAdditionalControls(Composite parent) {
		// TODO Auto-generated method stub

	}

	@Override
	protected Validator getValidator(TaskRepository repository) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	protected boolean isValidUrl(String url) {
		// TODO Auto-generated method stub
		return true;
	}

	/**
	 * Url doesn't need to be unique right now
	 */
	@Override
	protected String isUniqueUrl(String urlString) {
		return null;
	}

	@Override
	public boolean isPageComplete() {
		return valid;
	}
}
